from PyQt5.QtWidgets import *

from network.network import ServerSocket
from exception import DisconnectedError
from serverutils import *
from network.package import *

import sys
import logging

host = '127.0.0.1'
port = 7290
if len(sys.argv) > 1:
    port = int(sys.argv[1])

tempDir = "temp"

# logging.basicConfig(filename='example-server.log', level=logging.INFO)
logging.basicConfig(level=logging.INFO) # , format='%(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

ctrl = Controller("books", "temp")
controllerDict = {
    "booklist": ctrl.getBookList, 
    "upload": ctrl.upload,
    "download": ctrl.download,
    "bookinfo": ctrl.getMetadata,
    "content": ctrl.getChapterContent
}

def controller(pack, user):

    if isinstance(pack, JsonPackage):
        req = pack.data["type"]
    else:
        req = pack.head["type"]
    logger.debug(req)

    return controllerDict[req](pack, user)

server = ServerSocket(host, port)
logger.info("Server is running at {}:{}".format(*server.host))
try:
    server.run(controller)
except KeyboardInterrupt:
    logger.info("\nStopping server")
except Exception as e:
    logger.error(e)
finally:
    server.close()
